import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Enumeration;

// HttpServletRequest类的相关方法演示
@WebServlet("/showRequest")
public class ShowRequestServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 需要设置ContextType为text/html，下面的html代码才有效
        resp.setContentType("text/html; charset=utf-8");
        // 使用StringBuilder，把内容拼接在一起，然后写回resp的body中
        StringBuilder stringBuilder = new StringBuilder();

        stringBuilder.append(req.getProtocol());
        stringBuilder.append("<br>");
        stringBuilder.append(req.getMethod());
        stringBuilder.append("<br>");
        stringBuilder.append(req.getRequestURI());
        stringBuilder.append("<br>");
        stringBuilder.append(req.getContextPath());
        stringBuilder.append("<br>");
        stringBuilder.append(req.getQueryString());
        stringBuilder.append("<hr>");


        // 获取header里面的键headerName(使用getHeaderNames())和值headerValue(使用getHeader(键))
        Enumeration<String> headerNames = req.getHeaderNames();
        while (headerNames.hasMoreElements()){
            // 获取枚举中的header每个键值对的的键
            String headerName = headerNames.nextElement();
            // 获取枚举中的header每个键值对的的值
            String headerValue = req.getHeader(headerName);
            stringBuilder.append(headerName+":"+headerValue);
            stringBuilder.append("<br>");
        }


        resp.getWriter().write(stringBuilder.toString());
    }
}
